package com.ubhave.powertrackernof1;

import java.util.Date;

import com.ubhave.powertrackernof1.R;

//import android.app.Activity;
import android.support.v4.app.FragmentActivity;
//import android.app.DialogFragment;
import android.support.v4.app.DialogFragment;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class RTLWActivity extends FragmentActivity implements LoginDialogListener{
    
	//class to handle RTLW cards on info screen
	
	//LG and Settings vars
	SharedPreferences settings;
	SharedPreferences.Editor editor;
	LifeGuideConnector lgc;
	PageSensorLogger psl;
	PageLogger pl;
	
	//content vars
	String intervention;
	String usr;
	int initCount;
	int addCount;
	int newCount;
	String title;
	
	//These variable names are confusing but its how POWeR was designed
	String reasonsContent;
	String addReasonsContent;
	String newReasonsContent;
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.rtlw);
        
        //StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        //StrictMode.setThreadPolicy(policy);
        
        //set up settings and lgc
        settings=PreferenceManager.getDefaultSharedPreferences(getBaseContext());
        editor = settings.edit();
        lgc = new LifeGuideConnector(settings);
        
        //initialise content strings;
        reasonsContent="";
        addReasonsContent="";
        newReasonsContent="";
        
        //grab values from settings for making lgc calls
        usr = settings.getString("LifeGuideUser", "");
		intervention = settings.getString("LifeGuideInterventionId", "");
		
		if(settings.getBoolean("SensorsOn", false))    		
			psl = new PageSensorLogger(this);
		pl=new PageLogger(this);
		
		class AsyncLogAndRetrieve extends AsyncTask{

			@Override
			protected Object doInBackground(Object... params) {
				//Usage Logging
				/*editor.putString("usageLog", settings.getString("usageLog", "")+params[0].getClass().getSimpleName()+" "+new Date()+", ");
        		editor.commit();
        		if(!usr.equals("")&&!intervention.equals(""))
        			lgc.postVar(intervention, usr, "user", "appUsageLog", settings.getString("usageLog", ""),settings.getString("authkey",""));
        		else
        			Log.i("POWeR Tracker: ", "Log fail usr: "+usr+" int: "+intervention);*/
		
				try{
					pl.makeLog();
				
        			//Sensor Logging
        			if(settings.getBoolean("SensorsOn", false)){
						psl.makeLog();
        			}
        		
        			reasonsContent="";
                	addReasonsContent="";
                	newReasonsContent="";
                	initCount=0;
        			addCount=0;
        			newCount=0;
        		
        			String nameValue = lgc.getVar(intervention, usr, "user", "personsname",settings.getString("authkey",""));
        			if(nameValue!=null){
        				editor.putString("personsname", nameValue);
        				title = nameValue+"'s Reasons to Lose Weight Card";
        			}
        		
        		
        		
        		
        			for(int i = 0; i<6; i++){
                		String reason = lgc.getVar(intervention, usr, "user", "rtlw"+(i+1),settings.getString("authkey",""));
                		if(reason!=null){
                			editor.putString("rtlw"+(i+1),reason);
                			editor.commit();
                			reasonsContent +=reason+"\n";
                			initCount++;
                		}
                		else if(!settings.getString("rtlw"+(i+1), "").equals("")){
                			reasonsContent+=settings.getString("rtlw"+(i+1), "")+"\n";
                			initCount++;
                		}
                	}
        			if(!reasonsContent.equals(""))
        				reasonsContent=reasonsContent.substring(0, reasonsContent.length()-1);
        		
        			for(int i = 0; i<7; i++){
                		String reason = lgc.getVar(intervention, usr, "user", "additional"+(i+1),settings.getString("authkey",""));
                		if(reason!=null){
                			editor.putString("additional"+(i+1),reason);
                			editor.commit();
                			addReasonsContent+=reason+"\n";
                			addCount++;
            			}
                		else if(!settings.getString("additional"+(i+1), "").equals("")){
                			addReasonsContent+=settings.getString("additional"+(i+1), "")+"\n";
                			addCount++;
                		}
                	}
        			if(!addReasonsContent.equals(""))
        				addReasonsContent=addReasonsContent.substring(0, addReasonsContent.length()-1);
        		
        			for(int i = 0; i<8; i++){
                		String reason = lgc.getVar(intervention, usr, "user", "newreason"+(i+1),settings.getString("authkey",""));
                		if(reason!=null){
                			editor.putString("newreason"+(i+1),reason);
                			editor.commit();
                			newReasonsContent+=reason+"\n";
                			newCount++;
                		}
                		else if(!settings.getString("newreason"+(i+1), "").equals("")){
                			newReasonsContent+=settings.getString("newreason"+(i+1), "")+"\n";
                			newCount++;
                		}
                	}
        			if(!newReasonsContent.equals(""))
        				newReasonsContent=newReasonsContent.substring(0, newReasonsContent.length()-1);
        		
				} catch (PowerTrackerInvalidAuthKeyException e) {
					invalidKey();
				}
        		
        		return null;
			}
			
			protected void onPostExecute(Object result) {
				refreshContentValues();
		    }
		};
		//Async executed at end of onCreate to avoid clashes on accessing content vars
        
		
		//initialise the counters
		initCount=0;
		addCount=0;
		newCount=0;
        
		//Make the title using the users name
        //title = lgc.getVar(intervention, usr, "user", "personsname")+"'s Reasons to Lose Weight Card";
		title = settings.getString("personsname","")+"'s Reasons to Lose Weight Card";
		
        TextView titleTv = (TextView)findViewById(R.id.RTLWtitle);
        titleTv.setText(title);
        
        //Set up the initial reasons TextView by populating it with rtlw vars that have values from lgc		
        TextView initReasonsTv = (TextView)findViewById(R.id.RTLWreasonstext);
        
        for(int i = 0; i<6; i++){
        	//String reason = lgc.getVar(intervention, usr, "user", "rtlw"+(i+1));
        	String reason = settings.getString("rtlw"+(i+1),"");
        	if(reason!=""){
        		//initReasonsTv.setText(initReasonsTv.getText()+reason+"\n");
        		reasonsContent +=reason+"\n";
        		initCount++;
        	}
        }
        if(!reasonsContent.equals(""))
        	reasonsContent=reasonsContent.substring(0, reasonsContent.length()-1);
        initReasonsTv.setText(reasonsContent);
        
        //Check to see if the resulting TextView is blank, if so delete the title.
        /*if(initCount==0){
        	TextView initReasonsTitleTv = (TextView)findViewById(R.id.RTLWreasonstitle);
        	initReasonsTitleTv.setVisibility(initReasonsTitleTv.GONE);
        }*/
       
        //Set up the additional reasons TextView by populating it with additional vars that have values from lgc	
        TextView addReasonsTv = (TextView)findViewById(R.id.RTLWadditionaltext);
              
        for(int i = 0; i<7; i++){
        	//String reason = lgc.getVar(intervention, usr, "user", "additional"+(i+1));
        	String reason = settings.getString("additional"+(i+1),"");
        	if(reason!=""){
        		//addReasonsTv.setText(addReasonsTv.getText()+reason+"\n");
        		addReasonsContent+=reason+"\n";
        		addCount++;
    		}
        }
        if(!addReasonsContent.equals(""))
        	addReasonsContent=addReasonsContent.substring(0, addReasonsContent.length()-1);
        addReasonsTv.setText(addReasonsContent);
        
        //Check to see if the resulting TextView is blank, if so delete the title.
        /*if(addCount==0){
        	TextView addReasonsTitleTv = (TextView)findViewById(R.id.RTLWadditionaltitle);
        	addReasonsTitleTv.setVisibility(addReasonsTitleTv.GONE);
        }*/
        
        //Set up the new reasons TextView by populating it with additional vars that have values from lgc
        TextView newReasonsTv = (TextView)findViewById(R.id.RTLWnewtext);
        
        for(int i = 0; i<8; i++){
        	//String reason = lgc.getVar(intervention, usr, "user", "newreason"+(i+1));
        	String reason = settings.getString("newreason"+(i+1),"");
        	if(reason!=""){
        		//newReasonsTv.setText(newReasonsTv.getText()+reason+"\n");
        		newReasonsContent+=reason+"\n";
        		newCount++;
        	}
        }
        if(!newReasonsContent.equals(""))
        	newReasonsContent=newReasonsContent.substring(0, newReasonsContent.length()-1);
        newReasonsTv.setText(newReasonsContent);
        //Check to see if the resulting TextView is blank, if so delete the title.
        /*if(newCount==0){
        	TextView newReasonsTitleTv = (TextView)findViewById(R.id.RTLWnewtitle);
        	newReasonsTitleTv.setVisibility(newReasonsTitleTv.GONE);
        }*/
        
        //Async executed at end of onCreate to avoid clashes on accessing content vars
        new AsyncLogAndRetrieve().execute(this);
        
    }
    
    @Override
    protected void onPause() {
        super.onPause();
        if(psl!=null)
        	psl.stopLocationSensing();
    }
    
    @Override
    protected void onResume() {
        super.onResume();
        if(psl!=null)
        	psl.resumeLocationSensing();
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        	
    	switch (item.getItemId()) {
            case android.R.id.home:
                // app icon in action bar clicked; go home
                goHome();
                return true;
            case R.id.home:
                // app icon in options clicked; go home
            	goHome();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.o_menu, menu);
        return true;
    }
    
    public void goHome(){
    	Intent intent = new Intent(this, PowerTrackerActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    }
    
    public void refreshContentValues(){
    	
    	TextView titleTv = (TextView)findViewById(R.id.RTLWtitle);
        titleTv.setText(title);
        
        TextView initReasonsTv = (TextView)findViewById(R.id.RTLWreasonstext);
        initReasonsTv.setText(reasonsContent);
        /*if(initCount==0){
        	TextView initReasonsTitleTv = (TextView)findViewById(R.id.RTLWreasonstitle);
        	initReasonsTitleTv.setVisibility(initReasonsTitleTv.GONE);
        }*/
        
        TextView addReasonsTv = (TextView)findViewById(R.id.RTLWadditionaltext);
        addReasonsTv.setText(addReasonsContent);
        /*if(addCount==0){
        	TextView addReasonsTitleTv = (TextView)findViewById(R.id.RTLWadditionaltitle);
        	addReasonsTitleTv.setVisibility(addReasonsTitleTv.GONE);
        }*/
        
        TextView newReasonsTv = (TextView)findViewById(R.id.RTLWnewtext);
        newReasonsTv.setText(newReasonsContent);
        /*if(newCount==0){
        	TextView newReasonsTitleTv = (TextView)findViewById(R.id.RTLWnewtitle);
        	newReasonsTitleTv.setVisibility(newReasonsTitleTv.GONE);
        }*/
    }
    
    public void invalidKey(){
		DialogFragment dialog = new LoginDialog();
		Bundle errorBundle = new Bundle();
	    errorBundle.putString("error", "Your Authentication Key is invalid, expired, or is missing. Please Log In.");
	    dialog.setArguments(errorBundle);
	    //dialog.show(this.getFragmentManager(), "LoginDialog");
	    dialog.show(this.getSupportFragmentManager(), "LoginDialog");
	}
    
  	@Override
	public void onLoginDialogPositiveClick() {
		// TODO Auto-generated method stub
  		Log.i("POWeR Tracker Special: ","Clicked OK");
  		finish();
  		startActivity(getIntent());
	}


	@Override
	public void onLoginDialogNegativeClick() {
		// TODO Auto-generated method stub
		Log.i("POWeR Tracker Special: ","Clicked Cancel");
		goHome();
	}
    
}